package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallHistoriesService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * 用户服务
 */
@RestController
@RequestMapping("/wx/user")
@Validated
public class WxUserController {
    private final Log logger = LogFactory.getLog(WxUserController.class);

    @Autowired
    private LitemallOrderService orderService;

    @Autowired
    private LitemallUserService userService;


    /**
     * 用户个人页面数据
     * <p>
     * 目前是用户订单统计信息
     *
     * @param userId 用户ID
     * @return 用户个人页面数据
     */
    @GetMapping("index")
    public Object list(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("order", orderService.orderInfo(userId));
        return ResponseUtil.ok(data);
    }

    @Cacheable(cacheNames = "getUser",key = "#userId", condition = "#userId > 0")
    @GetMapping("getUser")
    public Object getUser(@RequestParam(defaultValue = "1") Integer userId) {
        LitemallUser byId = userService.findById(userId);
        Map<Object, Object> data = new HashMap<>();
        data.put("user", byId);
        return ResponseUtil.ok(data);
    }

    /**
     * 批量获取用户信息
     *
     * @param userIds 用户ID列表
     * @return 用户信息列表
     */
    @PostMapping("batchGetUsers")
    public Object batchGetUsers(@RequestBody List<Integer> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return ResponseUtil.badArgument();
        }

        Map<Integer, LitemallUser> userMap = new HashMap<>();
        List<LitemallUser> userList = new ArrayList<>();
        
        for (Integer userId : userIds) {
            if (userId != null && userId > 0) {
                LitemallUser user = userService.findById(userId);
                if (user != null) {
                    userMap.put(userId, user);
                    userList.add(user);
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("userMap", userMap);
        data.put("userList", userList);
        data.put("totalCount", userList.size());
        data.put("requestCount", userIds.size());
        
        return ResponseUtil.ok(data);
    }

    /**
     * 批量获取用户订单统计信息
     *
     * @param userIds 用户ID列表
     * @return 用户订单统计信息列表
     */
    @PostMapping("batchGetUserOrderInfo")
    public Object batchGetUserOrderInfo(@RequestBody List<Integer> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return ResponseUtil.badArgument();
        }

        // 限制批量查询数量，防止性能问题
        if (userIds.size() > 50) {
            return ResponseUtil.fail(400, "批量查询用户订单统计数量不能超过50个");
        }

        Map<Integer, Object> orderInfoMap = new HashMap<>();
        List<Map<String, Object>> orderInfoList = new ArrayList<>();
        
        for (Integer userId : userIds) {
            if (userId != null && userId > 0) {
                try {
                    Object orderInfo = orderService.orderInfo(userId);
                    LitemallUser user = userService.findById(userId);
                    
                    Map<String, Object> userOrderInfo = new HashMap<>();
                    userOrderInfo.put("userId", userId);
                    userOrderInfo.put("user", user);
                    userOrderInfo.put("orderInfo", orderInfo);
                    
                    orderInfoMap.put(userId, userOrderInfo);
                    orderInfoList.add(userOrderInfo);
                } catch (Exception e) {
                    logger.error("获取用户订单统计信息失败，userId: " + userId, e);
                    // 继续处理其他用户，不中断批量操作
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("orderInfoMap", orderInfoMap);
        data.put("orderInfoList", orderInfoList);
        data.put("successCount", orderInfoList.size());
        data.put("requestCount", userIds.size());
        
        return ResponseUtil.ok(data);
    }

    /**
     * 批量获取用户完整信息（包含用户基本信息和订单统计）
     *
     * @param userIds 用户ID列表
     * @return 用户完整信息列表
     */
    @PostMapping("batchGetUserFullInfo")
    public Object batchGetUserFullInfo(@RequestBody List<Integer> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return ResponseUtil.badArgument();
        }

        // 限制批量查询数量，防止性能问题
        if (userIds.size() > 30) {
            return ResponseUtil.fail(400, "批量查询用户完整信息数量不能超过30个");
        }

        Map<Integer, Map<String, Object>> userFullInfoMap = new HashMap<>();
        List<Map<String, Object>> userFullInfoList = new ArrayList<>();
        
        for (Integer userId : userIds) {
            if (userId != null && userId > 0) {
                try {
                    LitemallUser user = userService.findById(userId);
                    if (user != null) {
                        Object orderInfo = orderService.orderInfo(userId);
                        
                        Map<String, Object> fullInfo = new HashMap<>();
                        fullInfo.put("userId", userId);
                        fullInfo.put("user", user);
                        fullInfo.put("orderInfo", orderInfo);
                        
                        userFullInfoMap.put(userId, fullInfo);
                        userFullInfoList.add(fullInfo);
                    }
                } catch (Exception e) {
                    logger.error("获取用户完整信息失败，userId: " + userId, e);
                    // 继续处理其他用户，不中断批量操作
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("userFullInfoMap", userFullInfoMap);
        data.put("userFullInfoList", userFullInfoList);
        data.put("successCount", userFullInfoList.size());
        data.put("requestCount", userIds.size());
        
        return ResponseUtil.ok(data);
    }
}